const express = require('express')
const Result = require('../result/result')
const { queryGoods } = require('../mysql/goods')
const { queryCategoryTwo } = require('../mysql/category')
// const { queryImageByGoodsId } = require('../mysql/image')
const { queryGoodsPriceById, queryGoodsDiscountByIdAndPrice, queryGoodsImageIdByGoodsId, queryGoodsByImageId } = require('../mysql/goodsInfo')
const { NO_PERMISSION } = require('../result/reponseState')

const router = express.Router()

router.get('', async (req, res) => {
  try {
    const { page, keyword, categoryId, isPromo, isStock, key, isPriceDown } = req.query
    const resultArr = []
    const promiseArr = []
    const result = await queryGoods(page, keyword, categoryId, isPromo, isStock, key, isPriceDown)
    const pro = (e, eindex) => {
      return new Promise(async (resolve, reject) => {
        const imgId = (await queryGoodsImageIdByGoodsId(e.goods_id))[0].goods_image_id
        const goodsInfo = await queryGoodsByImageId(imgId)
        const obj = {
          type: 'goods',
          msg: {
            goodsInfo
          }
        }
        resultArr[eindex] = obj
        resolve()
      })
    }
    result.forEach((e, eindex) => {
      promiseArr.push(pro(e, eindex))
    })
    Promise.all(promiseArr).then(() => {
      res.send(Result.ok(resultArr))
    })
  } catch (error) {
    res.send(Result.error2(NO_PERMISSION, error))
  }
})

router.get('/category', (req, res) => {
  const keyword = req.query.keyword
  queryCategoryTwo(keyword).then((response) => {
    res.send(Result.ok(response))
  }, (err) => {
    res.send(Result.error2(NO_PERMISSION, err))
  })
})

module.exports = router
